package com.open.capacity.paper.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.common.auth.details.LoginAppUser;
import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.Paper;
import com.open.capacity.common.model.PaperQuestion;
import com.open.capacity.common.model.RateType;
import com.open.capacity.common.model.SysRole;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.paper.dao.PaperDao;
import com.open.capacity.paper.dao.PaperQuestionDao;
import com.open.capacity.paper.dao.RateTypeDao;
import com.open.capacity.paper.feign.UserFeignClient;
import com.open.capacity.paper.service.PaperService;
import com.open.capacity.paper.vo.PaperVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liangd
 * @since 2021-02-01 14:37
 */
@Service
@Slf4j
public class PaperServiceImpl extends ServiceImpl<PaperDao, Paper> implements PaperService {

    @Autowired
    private PaperDao paperDao;

    @Autowired
    private PaperQuestionDao paperQuestionDao;

    @Autowired
    private RateTypeDao rateTypeDao;

    @Resource
    private UserFeignClient userFeignClient;

    @Override
    public PageResult<PaperVo> getPapers(Map<String, Object> params) throws ServiceException {
        try {
            //设置分页信息，分别是当前页数和每页显示的总记录数
            if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null) {
                PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);
            }
            List<Paper> list = paperDao.findList(params);
            List<PaperVo> paperVoList = list.stream().map(paper -> {
                PaperVo paperVo = new PaperVo();
                BeanUtils.copyProperties(paper, paperVo);
                SysRole sysRole = userFeignClient.findById(paper.getFacegp().longValue());
                paperVo.setFacegpStr(sysRole.getName());
                LoginAppUser user = userFeignClient.findByUsername(paper.getPublis());
                paperVo.setPublisStr(user.getNickname());
                RateType rateType = rateTypeDao.getRateType(paper.getRtcode());
                paperVo.setRtcodeStr(rateType.getRtname());
                return paperVo;
            }).collect(Collectors.toList());

            PageInfo<PaperVo> pageInfo = new PageInfo<>(paperVoList);
            return PageResult.<PaperVo>builder().data(pageInfo.getList()).code(0).count(pageInfo.getTotal()).build();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updatePaper(Paper paper) throws ServiceException {
        try {
            paper.setUpdtim(new Date());
            int i = paperDao.updateById(paper);
            if (i > 0) {
                return Result.succeed("更新成功");
            }
            return Result.failed("更新失败");
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result savePaper(Paper paper) throws ServiceException {
        try {
            paper.setCretim(new Date());
            paper.setStatus(1);
            int i = paperDao.insert(paper);
            if (i > 0) {
                return Result.succeed("新增成功");
            }
            return Result.failed("新增失败");
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deletePaper(Integer papeid) throws ServiceException {
        try {
            List<PaperQuestion> list = new LambdaQueryChainWrapper<>(paperQuestionDao).eq(PaperQuestion::getPapeid, papeid).list();
            if (list.size()>0){
                return Result.failed("该问卷与问题已关联，请先移除关系，在进行操作！");
            }
            Paper paper = paperDao.selectById(papeid);
            paper.setStatus(2);
            paperDao.updateById(paper);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }
}
